from sqlalchemy import SmallInteger, String, Text, ForeignKey
from sqlalchemy.orm import mapped_column, Mapped, relationship

from models import BaseTable
from models.device import DeviceTable
from models.client import MqttClientTable


class RScriptDeviceTable(BaseTable):
    __tablename__ = "r_script_device"

    scriptId: Mapped[int] = mapped_column(ForeignKey("script.id", ondelete="CASCADE"))
    deviceNo: Mapped[int] = mapped_column(ForeignKey("device.no", ondelete="CASCADE"))


class RScriptMqttClientTable(BaseTable):
    __tablename__ = "r_script_mqtt_client"

    scriptId: Mapped[int] = mapped_column(ForeignKey("script.id", ondelete="CASCADE"))
    mqttClientId: Mapped[int] = mapped_column(ForeignKey("mqtt_client.id", ondelete="CASCADE"))


class ScriptTable(BaseTable):
    __tablename__ = "script"

    name: Mapped[str] = mapped_column(String(32), unique=True, comment="脚本名称")
    content: Mapped[str] = mapped_column(Text, comment="采集脚本")
    args: Mapped[int] = mapped_column(SmallInteger, default=1, comment="参数类型：1-单台设备 2-网关信息")
    mode: Mapped[str] = mapped_column(String(8), default="polling", comment="采集方式 polling-轮询 interval-定时触发 advanced-高级定时设置")
    hour: Mapped[str] = mapped_column(String(16), nullable=True, comment="每天第x小时触发, 取值范围0-23")
    minute: Mapped[str] = mapped_column(String(16), nullable=True, comment="每小时第x分钟触发, 取值范围0-59")
    second: Mapped[str] = mapped_column(String(16), nullable=True, comment="每分钟第x秒触发, 取值范围0-59")
    year: Mapped[str] = mapped_column(String(16), nullable=True, comment="x年触发, 4位数字，支持cron算数表达式，下同")
    month: Mapped[str] = mapped_column(String(16), nullable=True, comment="x月触发, 取值范围1-12")
    day: Mapped[str] = mapped_column(String(16), nullable=True, comment="x日触发, 取值范围1-31")
    week: Mapped[str] = mapped_column(String(16), nullable=True, comment="第x周触发, 取值范围1-53")
    day_of_week: Mapped[str] = mapped_column(String(16), nullable=True, comment="每周第x天触发, 取值范围0-6，或周的简写")

    devRelation: Mapped[list[RScriptDeviceTable]] = relationship("RScriptDeviceTable")
    mqttRelation: Mapped[list[RScriptMqttClientTable]] = relationship("RScriptMqttClientTable")
    devices: Mapped[list["DeviceTable"]] = relationship("DeviceTable", secondary="r_script_device", viewonly=True)
    mqttClients: Mapped[list["MqttClientTable"]] = relationship("MqttClientTable", secondary="r_script_mqtt_client", viewonly=True)
